package cn.easy.controller;

import cn.easy.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author 张澎_9970
 * @date 2021.12.13 下午 7:47 星期一
 * @desc:
 *  serviceInstance版本
 */
@RestController
@RequestMapping("consumer2")
public class UserController2 {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    public User findById(@PathVariable Integer id) {
        // 动态的从Eureka server中获取IP和端口
        List<ServiceInstance> instances = discoveryClient.getInstances("USER-PROVIDER");
        ServiceInstance serviceInstance = instances.get(0);
        return restTemplate.getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/user/" + id, User.class);
    }
}
